package com.qidian.server.socket;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.sql.Date;
import java.sql.Timestamp;

import org.apache.log4j.Logger;

import com.qidian.common.Constants;
import com.qidian.server.MServer;
import com.qidian.server.Status;

public class AnswerWorker implements Runnable{

    protected DatagramSocket serverSocket = null;
    protected DatagramPacket recvPacket = null ;
    protected String serverText   = null;
	protected byte[] buf = new byte[Constants.socket_buf_size];
	protected MServer mserver = MServer.getInstance() ;
	
    static Logger logger = Logger.getLogger(AnswerWorker.class) ;
    
    public AnswerWorker(DatagramSocket clientSocket, DatagramPacket recvData,String serverText) {
        this.serverSocket = clientSocket;
        this.serverText   = serverText;
        this.recvPacket = recvData ;
    }

    public void run() 
    {
		try 
		{		
	    	Status status = Status.OK ;
	        int port = recvPacket.getPort();
	        InetAddress addr = recvPacket.getAddress();
	        StringBuffer answer = null ;
	    	byte[] sendBuf = null;

	        byte[] recvData = recvPacket.getData() ;
	        String msgId = new String(recvData,0,recvPacket.getLength()) ;
	
	        long id = Long.parseLong(msgId) ;
	        answer = new StringBuffer(8) ;
	        status = mserver.p2s_getAnswer(id, null, null, answer) ;
	
	        if (status == Status.OK)
				sendBuf = (id+"#"+answer).getBytes(Constants.answer_charset) ;
	        else
	        	sendBuf = (id+"#"+status.toString()).getBytes() ;
	        
	        DatagramPacket sendPacket= new DatagramPacket(sendBuf , sendBuf.length , addr , port );
			serverSocket.send(sendPacket);

		} catch (Exception e) {
//			logger.error(e.getMessage()+":"+recvPacket.getAddress()) ;
		}

    }
    
    public static void main(String []args) throws UnsupportedEncodingException
    {
    	String strLong = "试" ;
//    	long id = Long.parseLong(strLong) ;
//    	System.out.println(id) ;
    	byte[] content = strLong.getBytes("US-ASCII") ;
    	
    	content = strLong.getBytes("ascii") ;
    	for(int i= 0 ; i < content.length ; i ++)
    		System.out.println(content[i]);
    	System.out.println(content.length) ;
    	
    	content = strLong.getBytes("UTF8") ;
    	for(int i= 0 ; i < content.length ; i ++)
    		System.out.println(content[i]);
    	System.out.println(content.length) ;
    	
    	content = strLong.getBytes("gb2312") ;
    	for(int i= 0 ; i < content.length ; i ++)
    		System.out.println(content[i]);
    	System.out.println(content.length) ;
    	
    	content = strLong.getBytes() ;
    	for(int i= 0 ; i < content.length ; i ++)
    		System.out.println(content[i]);
    	System.out.println(content.length) ;
    }
    
}